//
//  StaffEditController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/21.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "StaffEditController.h"
#import "OrderStaffSelectController.h"

#define ACCOUNT_MAX_CHARS 16

@interface StaffEditController ()<UIAlertViewDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UILabel *staffName;
@property (weak, nonatomic) IBOutlet UILabel *staffMobile;
@property (weak, nonatomic) IBOutlet UITextField *staffNameLabel;
@property (weak, nonatomic) IBOutlet UITextField *staffMobileLabel;
@property (weak, nonatomic) IBOutlet UIButton *setDefaultStaffBtn;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UINavigationItem *nav;
@property (weak, nonatomic) IBOutlet UILabel *isDefaultLabel;

- (IBAction)saveAction:(id)sender;
- (IBAction)setDefaultStaffAction:(id)sender;

@end

@implementation StaffEditController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.setDefaultStaffBtn setImage:[UIImage imageNamed:@"check2"] forState:UIControlStateNormal];
    [self.setDefaultStaffBtn setImage:[UIImage imageNamed:@"check2_on"] forState:UIControlStateSelected];
    
    self.staffNameLabel.delegate = self;
    self.staffMobileLabel.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    
    //注册通知,监听键盘消失事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden) name:UIKeyboardDidHideNotification object:nil];
    
    [self.saveBtn setBackgroundColor:TextColorImportButton];
    
    UITapGestureRecognizer *upGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setDefaultStaffAction:)];
    self.isDefaultLabel.userInteractionEnabled=YES;
    upGesture.numberOfTapsRequired=1;
    //设置手指数 单指
    upGesture.numberOfTouchesRequired=1;
    // titleLabel添加手势识别
    [self.isDefaultLabel addGestureRecognizer:upGesture];
    if( self.staff != nil ) {
        self.staffNameLabel.text = self.staff.name;
        self.staffMobileLabel.text = self.staff.telephone;
        
        self.setDefaultStaffBtn.selected = self.staff.isDefault;
        
        self.nav.title = @"编辑配送员";
    } else {
        self.nav.title = @"新增配送员";
        self.saveBtn.titleLabel.text = @"确定新增";
        [self.saveBtn setTitle:@"确定新增" forState:UIControlStateNormal];
        [self.saveBtn setTitle:@"确定新增" forState:UIControlStateSelected];
    }
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.staffMobileLabel) {
        if (string.length == 0) return YES;
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }
    return YES;
}


- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    for (UITableViewController *controller in self.navigationController.viewControllers) {
        
        if ([controller isKindOfClass:[OrderStaffSelectController class]])
        {
            [self.navigationController popToViewController:controller animated:YES];
            return;
        }
    }
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1]  animated:YES];
}

// 键盘弹出时
-(void)keyboardDidShow:(NSNotification *)notification
{
    //获取键盘高度
    NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect;
    
    [keyboardObject getValue:&keyboardRect];
    
    //设置view的frame，往上平移
    [self.saveBtn setFrame:CGRectMake(0, self.view.frame.size.height - keyboardRect.size.height - 60, self.view.bounds.size.width, 60)];
    
    //    [UIView commitAnimations];
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.staffMobileLabel resignFirstResponder];
}
-(void)keyboardDidHidden
{
    //设置view的frame，往下平移
    [self.saveBtn setFrame:CGRectMake(0, self.view.frame.size.height - 60, self.view.bounds.size.width, 60)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)setDefaultStaffAction:(id)sender {
    self.setDefaultStaffBtn.selected = !self.setDefaultStaffBtn.selected;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)saveAction:(id)sender {
    if ([NSString isNilOrEmptyOrWhitespace:self.staffNameLabel.text]) {
        [JFBUIAnimation errorInputTips:self.staffName animation:TipsBounces];
        [JFBUIAnimation alertTips: @"姓名不能为空"];
        return;
    }
    if ([NSString isNilOrEmptyOrWhitespace:self.staffMobileLabel.text] ) {
        [JFBUIAnimation errorInputTips:self.staffMobile animation:TipsBounces];
        [JFBUIAnimation alertTips: @"电话号码不能为空"];
        return;
    }
    if (![self.staffMobileLabel.text isValidMobileNumber]) {
        [JFBUIAnimation errorInputTips:self.staffMobile animation:TipsBounces];
        [JFBUIAnimation alertTips: @"电话号码不合法"];
        return;
    }
    if(self.staff == nil ){
        JFBStaffDS *staff = [[JFBStaffDS alloc] init];
        staff.name = self.staffNameLabel.text;
        staff.telephone = self.staffMobileLabel.text;
        staff.isDefault = self.setDefaultStaffBtn.selected;
            
        [JFBStaffDS addStaff:^(BOOL isSuccess, NSString *message, NSError *error) {
//            [self.delegate reload];
            [JFBUIAnimation alertTips:message];
            [self.navigationController popViewControllerAnimated:TRUE];
        } staff:staff];
        
    }else {
        self.staff.name = self.staffNameLabel.text;
        self.staff.telephone = self.staffMobileLabel.text;
        self.staff.isDefault = self.setDefaultStaffBtn.selected;

        [JFBStaffDS updateStaff:^(BOOL isSuccess, NSString *message, NSError *error) {
//            [self.delegate reload];
            [JFBUIAnimation alertTips:message delegate:self];
            [self.navigationController popViewControllerAnimated:TRUE];
            
        } staff:self.staff ];
    }
    
    
    
}
@end
